import { useModel } from "@/utils/useModel";
import { ElButton, ElTag } from "element-plus";
import { defineComponent } from "vue";
import { $tablePropEditor } from "./service";

const [Button, Tag] = [ElButton, ElTag];

export const TablePropEditor = defineComponent({
  name: "table-prop-editor",
  props: {
    modelValue: { type: Array },
    propConfig: { type: Object },
  },
  setup(props, ctx) {
    // 封装jsx， 实现数据双向绑定
    const model = useModel(
      () => props.modelValue,
      (val) => ctx.emit("update:modelValue", val)
    );

    const onClick = async () => {
      console.log("click...");
      // 打开弹层，并传入配置和data
      const data = await $tablePropEditor({
        config: props.propConfig,
        data: props.modelValue || [],
      });
      // 将弹层的数据写入
      model.value = data;
    };

    return () => (
      <div>
        {(!model.value || model.value.length === 0) && (
          <Button onClick={onClick} type="primary">
            添加
          </Button>
        )}
        {(model.value || []).map((item) => (
          <Tag onClick={onClick}>{item[props.propConfig.table?.showKey || ""]}</Tag>
        ))}
      </div>
    );
  },
});
